package org.example.codeservce.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.codeservce.comm.Q;
import org.example.codeservce.dao.UserDao;
import org.example.codeservce.entity.User;
import org.example.codeservce.service.UserService;
import org.example.codeservce.util.PasswordEncryp;
import org.springframework.stereotype.Service;

/**
 * (User)表服务实现类
 *
 * @author LiQing
 * @since 2024-05-15 11:48:12
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService
{

    @Override
    public Q login(String username, String password)
    {
        // 根据用户名获取用户信息
        User user = getUserByUsername(username);

        // 用户不存在
        if (user == null)
        {
            throw new IllegalArgumentException("用户不存在!");
        }

        // 校验密码
        if (!PasswordEncryp.IfPassowrd(password, user.getPassword()))
        {
            throw new IllegalArgumentException("用户密码不正确!");
        }

        // 登录成功
        StpUtil.login(user.getId());
        return Q.ok().q("token", StpUtil.getTokenValue()).q("user", user);
    }

    /**
     * 注册
     *
     * @param code
     * @param codeStr
     * @return
     */
    @Override
    public Q enroll(User user, String code, String codeStr)
    {
        // 校验验证码
        if (!PasswordEncryp.IfPassowrd(code, codeStr))
        {
            throw new IllegalArgumentException("验证码不正确!");
        }

        User userByUsername = getUserByUsername(user.getUsername());
        if (userByUsername != null)
        {
            throw new IllegalArgumentException("用户名存在!");
        }
        user.setPassword(PasswordEncryp.getPaawordEncryp(user.getPassword()));
        boolean save = save(user);
        return Q.ifBody(save).q("user",user);
    }

    // 根据用户名获取用户信息
    private User getUserByUsername(String username)
    {
        return getOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getUsername, username)
        );
    }
}

